package com.ts.api.module.common.controller;

import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.tree.TreeUtils;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.common.entity.AjaxResult;
import com.ts.api.common.localcache.CommonCache;
import com.ts.api.common.localcache.DistrictCache;
import com.ts.api.module.common.entity.DistrictPO;
import com.ts.api.module.common.entity.vo.RespAppDistrictVO;
import com.ts.api.module.common.entity.vo.RespDistrictVO;
import com.ts.api.module.common.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 *  地区编码相关
 */
@RestController
@RequestMapping("/common/district")
public class DistrictController {

    @Autowired
    private DistrictService districtService;

    /**
     *  H5-返回前端特定地区编码
     *
     *  @return ResultVO
     */
    @GetMapping("/list")
    public ResponseEntity<String> list() {
        RespDistrictVO respDistrictVO = CommonCache.H5_DISTRICT_MAP.get(DistrictCache.H5_DISTRICT_FORM_KEY, () -> RespDistrictVO.convertVO(districtService.list()));
        AjaxResult ajaxResult = AjaxResult.success(respDistrictVO);
        // 解决微信小程序没有CONTENT_LENGTH响应头会失败的问题
        String body = JsonUtils.toJson(ajaxResult);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.getBytes().length))
                .body(body);
    }

    /**
     *  APP-返回前端特定地区编码
     *
     *  @return ResultVO
     */
    @GetMapping("/listApp")
    public ResultVO<Object> listApp() {
        List<Map<String, Object>> respDistrictVO = CommonCache.APP_DISTRICT_MAP.get(DistrictCache.APP_DISTRICT_FORM_KEY, () -> {
            List<DistrictPO> list = districtService.list();
            List<RespAppDistrictVO> respAppDistrictVOS = CopyUtils.copyList(list, RespAppDistrictVO.class);
            return TreeUtils.create(respAppDistrictVOS, 2, true);
        });
        return ResultVO.suc(respDistrictVO);
    }
}
